from django.shortcuts import render

from django.http import HttpResponse

from core import film_core

FilmSearch = film_core.FilmSearch


# Create your views here.


def index(request):

    context = {}

    # return render(request, 'index.html', context)

    return render(request, 'film_app/index.html', context)


def search(request):
    if request.method == 'POST':  # 如果提交方式是POST

        keyword = request.POST.get('keyword')  # 获取搜索的关键字

        # print(keyword)

        search_info = FilmSearch().get_search_info(keyword)

        context = {'search_list': search_info}

        return render(request, 'film_app/single-page.html', context)


    else:  ##如果提交方式是GET

        context = {}

        return render(request, 'film_app/index.html', context)


def www123ku(request):
    value = request.GET.get('m')  # m表示要播放的电影名称

    num = request.GET.get('num')  # num 表示要播放哪一集视频

    # print(value)

    if value == None:

        context = {}

        return render(request, 'film_app/index.html', context)

    else:
        url = 'http://www.123ku.com/?m={}'.format(value)

        # print(url)

        info = FilmSearch().get_film_info(url)

        url_list = info['show_url']  # 获取数据

        film_name = info['name']

        print(film_name)

        ###########数据清理#############

        joint_url = '/app/123ku/?m=vod-detail-id-13518.html&num={}'

        url_m3u8 = []

        for i in url_list:  # 把以m3u8结尾的视频链接提出来

            if i[0].endswith('m3u8'):
                url_m3u8.append(i)

        if num == None:  # 表示无num参数时，默认播放第一集

            num = 0

        url_show = []

        joint_url = '/app/123ku/?m={}&num={}'

        for i in range(len(url_m3u8)):  # 生成渲染时需要的链接

            show = (joint_url.format(value, i), url_m3u8[i][1])

            url_show.append(show)

        # print(url_show)

        context = {'url_list': url_show, 'show': url_m3u8[int(num)],'name':film_name}

        return render(request, 'film_app/single-video.html', context)













